package com.ddkj.netty.server.socket.airServer;

import com.ddkj.netty.Setting;
import com.ddkj.netty.redis.RedisUtil;
import com.ddkj.netty.server.TCPAddress;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.AttributeKey;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * TCPByteHandler
 */
public class TCPAirServerHandler extends SimpleChannelInboundHandler<String> {

    private static final Log log = LogFactory.getLog(TCPAirServerHandler.class);

    //会话
    public static final AttributeKey<TCPAddress> KEY = AttributeKey.valueOf(Setting.SOCKET_DDKJ_AIR_NETTY);

    //存储channel
    public static Map<String, Channel> channelMap = new HashMap<>();

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {

        TCPAddress tcpAddress = new TCPAddress(ctx.channel());
        log.info(Setting.AIR_SERVER_NAME + "client_ip--> " + tcpAddress.getClientIP() + " 【上线】");
        ctx.channel().attr(KEY).set(tcpAddress);
        //存储channel
        channelMap.put(tcpAddress.getClientIP(), ctx.channel());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String s) throws Exception {

        //返回数据
        String data = null;

        //处理Channel
        Channel receiveChannel = null;

        //获取用户数据
        TCPAddress tcpAddress = ctx.channel().attr( KEY).get();
        String clientIP = tcpAddress.getClientIP();//ip

        //读取数据
        log.info(Setting.AIR_SERVER_NAME + "client_ip--> " + clientIP + " 【数据】" + s);

        if (s.equals("airport")) {
            String myClientIP = RedisUtil.get(Setting.DDKJ_NETTY_AIR_SOCKET_HEADER + s);
            if (myClientIP == null) {
                RedisUtil.set(Setting.DDKJ_NETTY_AIR_SOCKET_HEADER + s, clientIP);
            }
            String sStr = RedisUtil.get(clientIP);
            if (sStr == null) {
                RedisUtil.set(clientIP, Setting.DDKJ_NETTY_AIR_SOCKET_HEADER + s);
            }
        }else if (s.contains("#")){
            String[] strings = s.split("&");
            for (String str : strings) {
                String number = str.substring(str.indexOf("#") + 1, str.lastIndexOf("@"));
                String dxClientIP = RedisUtil.get(Setting.DDKJ_NETTY_AIR_SOCKET_HEADER + number);
                if (dxClientIP == null) {
                    RedisUtil.set(Setting.DDKJ_NETTY_AIR_SOCKET_HEADER + number, clientIP);
                }
                String num = RedisUtil.get(clientIP);
                if (num == null) {
                    RedisUtil.set(clientIP, Setting.DDKJ_NETTY_AIR_SOCKET_HEADER + number);
                }
                String myClientIP = RedisUtil.get(Setting.DDKJ_NETTY_AIR_SOCKET_HEADER + Setting.AIR_SERVER_CODE);
                receiveChannel = channelMap.get(myClientIP);
                receiveChannel.writeAndFlush(str + "&");
            }
        }else if (s.contains("$")){
            String number = s.substring(s.indexOf("$") + 1, s.lastIndexOf("@"));
            String dxClientIP = RedisUtil.get(Setting.DDKJ_NETTY_AIR_SOCKET_HEADER + number);
            receiveChannel = channelMap.get(dxClientIP);
            String message = s.substring(s.indexOf("@") + 1, s.lastIndexOf("&"));
            receiveChannel.writeAndFlush(message);
        }

    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        TCPAddress tcpAddress = new TCPAddress(ctx.channel());
        String clientIP = tcpAddress.getClientIP();
        removeIP(clientIP);
        log.info(Setting.AIR_SERVER_NAME + "client_ip--> " + clientIP + " 【下线】");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

        log.error("异常消息为-------->" + cause);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        log.info("什么鬼<userEventTriggered>------>" + evt);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        super.channelReadComplete(ctx);
        ctx.flush();
    }


    //清除数据
    protected void removeIP(String ipURI) {

        String whos = RedisUtil.get(ipURI);

        if (whos != null) {
            RedisUtil.remove(whos);
        }
        RedisUtil.remove(ipURI);
        //清空存储Map
        channelMap.remove(ipURI);

    }


}
